import Vue from "vue";
import { getAction } from '@/api/manage';
import moment from 'moment';

function aliOss(){
  return new Promise((resolve, reject) => {
    // 过期前5分钟重新请求
    if(Vue.ls.get('aliOssauthInfo')){
      let expirationTime = Vue.ls.get('aliOssauthInfo').expiration;
      expirationTime = moment(expirationTime);
      let nowTime = moment();
      if(nowTime.isBefore(expirationTime) && expirationTime.diff(nowTime, 'minutes') > 5){
        resolve();
        return;
      }
    }
    getAction('/sys/file/oss/sts').then(res => {  
      if (res.success) {
        let authInfo = res.result || {}
        Vue.ls.set('aliOssauthInfo', authInfo);
        let time = 12 * 60 * 60 * 1000 - 5 * 60 * 1000;
        let timer = setTimeout(() => {
          clearTimeout(timer);
          timer = null;
          aliOss();
        }, time)

        resolve();
      } else {
        Vue.prototype.$message.warning(res.message)
      }
    }).finally(() => {
      if(!Vue.ls.get('aliOssauthInfo')){
        Vue.prototype.$message.warning('获取授权失败！')
      }
    })
  })
}

export default aliOss;
